package com.kfm.bootmp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kfm.bootmp.entity.Goods;
import com.kfm.bootmp.entity.GoodsQuery;
import com.kfm.bootmp.service.GoodsService;
import com.kfm.bootmp.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "商品管理")
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @GetMapping
    @ApiOperation("查询商品列表")
    public R getList(GoodsQuery goodsQuery, @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "5") Integer size){
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        if (goodsQuery.getName() != null){
            wrapper.like("name", goodsQuery.getName());
        }
        if (goodsQuery.getMinPrice() != null){
            wrapper.ge("price", goodsQuery.getMinPrice());
        }
        if (goodsQuery.getMaxPrice() != null){
            wrapper.le("price", goodsQuery.getMaxPrice());
        }
        Page data = goodsService.page(Page.of(page, size), wrapper);
        return R.ok("查询成功").put("data", data);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据编号查询商品详情")
    public R get(@PathVariable Integer id){
        return R.ok("查询成功").put("data", goodsService.getById(id));
    }

    @PostMapping
    @ApiOperation("新增商品")
    public R add(Goods goods){
        goodsService.save(goods);
        return R.ok("新增成功");
    }


    @PutMapping
    public R update(Goods goods){
        goodsService.updateById(goods);
        return R.ok("修改成功");
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){
        goodsService.removeById(id);
        return R.ok("删除成功");
    }
}
